package com.pet.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.pet.common.constant.ResponseCode;
import com.pet.common.model.ResponseResult;
import com.pet.system.constant.ResourceStatus;
import com.pet.system.domain.entity.SysResource;
import com.pet.system.service.ISysResourceService;
import com.pet.system.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源控制器 1、资源分页查询（列表分页展现-平铺，不常用） 2、资源排序展示（排序处理后，前端树形） 3、资源菜单树(可根据parentId) 4、新增资源（菜单、按钮）、修改 & 删除 -
 * 按钮不允许包含子节点
 *
 * @author Centaurea
 */
@Api(tags = "资源管理", description = "菜单、按钮的CRUD功能")
@RestController
@RequestMapping("resource")
@AllArgsConstructor
public class ResourceController {
  private final ISysResourceService resourceService;

  @ApiOperation("资源信息转字典格式")
  @GetMapping("/dictionary")
  public ResponseResult dictionary(Integer parentId, Integer type, String status) {
    Map<String, Object> params = new HashMap<>(3);
    params.put("parentId", parentId);
    params.put("type", type);
    params.put("status", status);
    List<SysResource> list = resourceService.queryList(params);
    List<Map<String, Object>> res = new ArrayList<>();
    list.forEach(
        record -> {
          Map<String, Object> item = new HashMap<>(5);
          item.put("value", record.getId());
          item.put("label", record.getName());
          item.put("category", record.getType());
          item.put("id", record.getId());
          item.put("parentId", record.getParentId());
          res.add(item);
        });
    return ResponseResult.success(ResponseCode.WEB_200, res);
  }

  /**
   * @param parentId xx
   * @param type xx
   * @param searchWord xx
   * @param status xx
   * @return xx
   */
  @ApiOperation("资源列表集合")
  @GetMapping("/list")
  @RequiresPermissions("sys:resource:list")
  public ResponseResult query(Integer parentId, Integer type, String searchWord, String status) {
    Map<String, Object> params = new HashMap<>(4);
    params.put("parentId", parentId);
    params.put("type", type);
    params.put("status", status);
    params.put("searchWord", searchWord);
    List<SysResource> sysResources = resourceService.queryList(params);
    return ResponseResult.success(ResponseCode.WEB_200, sysResources);
  }

  /**
   * 获取树形资源（菜单 + 按钮， 通过 type 可过滤）
   *
   * @param parentId xx
   * @param type xx
   * @param searchWord xx
   * @param status xx
   * @return xx
   */
  @ApiOperation("资源树形格式集合")
  @GetMapping("/tree")
  @RequiresPermissions("sys:resource:list")
  public ResponseResult queryTree(
      Integer parentId, Integer type, String searchWord, String status) {
    Map<String, Object> params = new HashMap<>(4);
    params.put("parentId", parentId);
    params.put("type", type);
    params.put("searchWord", searchWord);
    params.put("status", status);
    JSONArray objects = resourceService.queryTree(params);
    return ResponseResult.success(ResponseCode.WEB_200, objects);
  }

  /**
   * 新增资源
   *
   * @param resource xx
   */
  @ApiOperation("新增资源")
  @PostMapping
  @RequiresPermissions("sys:resource:save")
  public ResponseResult save(SysResource resource) {
    resourceService.add(resource);
    return ResponseResult.success(ResponseCode.WEB_200);
  }

  /**
   * 修改资源
   *
   * @param resource xx
   * @return xx
   */
  @ApiOperation("修改资源")
  @PutMapping
  @RequiresPermissions("sys:resource:update")
  public ResponseResult update(SysResource resource) {
    resourceService.update(resource);
    return ResponseResult.success(ResponseCode.WEB_200);
  }

  @ApiOperation("修改资源状态")
  @PutMapping("/updateStatus")
  @RequiresPermissions({"sys:resource:disabled", "sys:resource:useable"})
  public ResponseResult updateStatus(Integer id, Integer status) {
    if (ResourceStatus.DISABLED.getStatus() != status) {
      status = ResourceStatus.NORMAL.getStatus();
    }
    SysResource entity = resourceService.get(id);
    if (entity == null) {
      return ResponseResult.error("记录不存在或已删除");
    }
    entity.setStatus(status);
    boolean update = resourceService.update(entity);
    return ResponseResult.success(ResponseCode.WEB_200, update);
  }

  /**
   * （批量）删除资源
   *
   * @param ids xx
   * @return xx
   */
  @ApiOperation("删除资源")
  @DeleteMapping("/{ids}")
  @RequiresPermissions("sys:resource:delete")
  public ResponseResult delete(@PathVariable("ids") String ids) {
    resourceService.delete(StringUtil.parseInteger(ids));
    return ResponseResult.success(ResponseCode.WEB_200);
  }
}
